﻿/// <reference name="MicrosoftAjax.js"/>
/// <reference name="Telerik.Web.UI.Common.Core-vsdoc.js" assembly="Telerik.Web.UI" />
/// <reference path="~/Clients/Scripts/jQuery/jquery-1.6.1-vsdoc.js"/>
/// <reference path="~/Clients/Scripts/jQuery/jquery.ajaxmanager-3.12.debug.js"/>
/// <reference path="~/Clients/Scripts/jQuery/jquery.json.debug.js"/>
/// <reference path="~/Clients/Scripts/jQuery/jquery.component.debug.js"/>
/// <reference path="~/Clients/Scripts/globals.debug.js"/>
/// <reference path="~/Clients/Scripts/errorHandling.debug.js"/>
/// <reference path="~/Clients/Scripts/loadingPanels.debug.js"/>
/// <reference path="~/Clients/Scripts/common.debug.js"/>
/// <reference path="~/Clients/Scripts/jqueryLookup.debug.js"/>

Type.registerNamespace("GreeNova");

GreeNova.GridPagerVisibility = function() { };
GreeNova.GridPagerVisibility.prototype =
{
    Hidden: 0,
    Visible: 1,
    OnlyIfNecessary : 2
}
GreeNova.GridPagerVisibility.registerEnum("GreeNova.GridPagerVisibility");

GreeNova.Utils = new function() {
    this.dummyFunc = function() {
    };

    this.stopPropagation = function(event) {
        try {
            event.cancelBubble = true;
            if (event.stopPropagation)
                event.stopPropagation();
        }
        catch (e) { }
    };
    this.disableEnterKey = function disableEnterKey(e) {
        var key;
        if (window.event)
            key = window.event.keyCode; //IE
        else
            key = e.which; //firefox     
        return (key != 13);
    };

    this.toServerDateStr = function(date) {
        ///	<returns type="String" />
        if (!date)
            return null;
        function f2(n) {
            return n < 10 ? '0' + n : n;
        }
        function f7(n) {
            var str = n + '0000000';
            return str.substr(0, 7);
        }
        if (date instanceof Date) {
            return '@Date(' +
                date.getFullYear() + '-' +
                f2(date.getMonth() + 1) + '-' +
                f2(date.getDate()) + 'T' +
                f2(date.getHours()) + ':' +
                f2(date.getMinutes()) + ':' +
                f2(date.getSeconds()) + '.' +
                f7(date.getMilliseconds()) + ')@'
        }
        else {
            debugger;
            throw "Not a date"
        }
    };

    this.fromServerDateStr = function(date) {
        ///	<returns type="Date" />
        if (!date)
            return date;
        if (typeof date === 'string') {
            var dateRegEx = new RegExp('^@Date\\((\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d{7})\\)@$');
            var d = dateRegEx.exec(date);
            if (d)
                return new Date(+d[1], +d[2] - 1, +d[3], +d[4], +d[5], +d[6], ('0.' + d[7]) * 1000);
            debugger;
            throw 'wrong format';
        }
        else {
            debugger;
            throw "Not a string";
        }
    };

    this.isNoU = function(obj) {
        ///	<returns type="Boolean" />
        return (obj === null || obj === undefined);
    };

    this.isNNoU = function(obj) {
        ///	<returns type="Boolean" />
        return (obj !== null && obj !== undefined);
    };

    this.Array = new function() {
        this.last = function(array) {
            if (!array.length) {
                debugger;
                throw "array doesn't have length";
            }
            if (array.length > 0)
                return array[array.length - 1];
            return undefined;
        };

        _sortNumbersFunc = function(a, b) {
            return a - b;
        };

        this.sortNumbers = function(array) {
            if (array)
                array.sort(_sortNumbersFunc);
        };

        this.compareNumbers = function(array1, array2) {
            ///	<returns type="Boolean" />
            if (!array1 && !array2)
                return true;
            if ((!array1 && array2) || (array1 && !array2) || (array1.length !== array2.length))
                return false;

            var a1 = array1.slice();
            var a2 = array2.slice();

            this.sortNumbers(a1);
            this.sortNumbers(a2);

            for (var i = 0; i < a1.length; i++) {
                var it1 = a1[i];
                var it2 = a2[i];
                if (it1 !== it2)
                    return false;
            }
            return true;
        };

        this.toSeparatedString = function(array, separator) {
            ///	<returns type="String" />
            if (array.length === 0)
                return '';
            return array.join(separator || '_');
        };

        this.fromSeparatedString = function(str, separator) {
            ///	<returns type="Array" />
            if (!str || str === '')
                return [];
            return str.split(separator || '_');
        };
    };


    this.RadTreeView = new function() {
        _getSelectedNodes = function(nodes, result) {
            if (!nodes)
                return;
            for (var i = 0; i < nodes.get_count(); i++) {
                var node = nodes.getNode(i);
                var cs = node.get_checkState();
                if (cs == Telerik.Web.UI.TreeNodeCheckState.Checked)
                    result.push(node);
                else
                    this._getSelectedNodes(node.get_nodes(), result);
            }
        };

        this.getSelectedNodes = function(treeview) {
            var result = [];
            if (!treeview || !Telerik.Web.UI.RadTreeView.isInstanceOfType(treeview))
                return result;
            _getSelectedNodes(treeview.get_nodes(), result);
            return result;
        };

        this.getNodePath = function(node, separator) {
            if (!node || !Telerik.Web.UI.RadTreeNode.isInstanceOfType(node))
                return '';
            var pp = this.getNodePath(node.get_parent());
            var name = node.get_text();
            if (pp != '')
                return pp + (separator || ' > ') + name;
            else
                return name;
        };

        _collapseAll = function(nodes) {
            if (!nodes || !Telerik.Web.UI.RadTreeNodeCollection.isInstanceOfType(nodes))
                return;
            for (var i = 0; i < nodes.get_count(); i++) {
                var n = nodes.getNode(i);
                n.collapse();
                _collapseAll(n.get_nodes());
            }
        };

        this.collapseAll = function(treeview) {
            if (!treeview || !Telerik.Web.UI.RadTreeView.isInstanceOfType(treeview))
                return;
            _collapseAll(treeview.get_nodes());
        };

        _uncheckAll = function(nodes) {
            if (!nodes || !Telerik.Web.UI.RadTreeNodeCollection.isInstanceOfType(nodes))
                return;
            for (var i = 0; i < nodes.get_count(); i++) {
                var n = nodes.getNode(i);
                n.uncheck();
                _uncheckAll(n.get_nodes());
            }
        };

        this.uncheckAll = function(treeview) {
            if (!treeview || !Telerik.Web.UI.RadTreeView.isInstanceOfType(treeview))
                return;
            _uncheckAll(treeview.get_nodes());
        };

        _expandTillChecked = function(nodes) {
            if (!nodes || !Telerik.Web.UI.RadTreeNodeCollection.isInstanceOfType(nodes))
                return;
            for (var i = 0; i < nodes.get_count(); i++) {
                var n = nodes.getNode(i);

                var cs = n.get_checkState();
                if (cs == Telerik.Web.UI.TreeNodeCheckState.Indeterminate) {
                    n.expand();
                    _expandTillChecked(n.get_nodes());
                }
            }
        };

        this.expandTillChecked = function(treeview) {
            if (!treeview || !Telerik.Web.UI.RadTreeView.isInstanceOfType(treeview))
                return;
            var nodes = treeview.get_nodes();
            _collapseAll(nodes);
            _expandTillChecked(nodes);
        };
    };

    this.RadGrid = new function() {
        this._radGrids = [];
        this._radGridsCounts = [];

        this._getGrid = function(grid) {
            ///	<returns type="Telerik.Web.UI.RadGrid" />
            if (grid && GreeNova.JqueryLookup.isInstanceOfType(grid))
                grid = grid.component();
            if (!grid || !Telerik.Web.UI.RadGrid.isInstanceOfType(grid)) {
                debugger;
                throw "Not a 'Telerik.Web.UI.RadGrid'";
            }
            return grid;
        };

        this._getGridMT = function(grid) {
            ///	<returns type="Telerik.Web.UI.GridTableView" />
            if (grid && GreeNova.JqueryLookup.isInstanceOfType(grid))
                grid = grid.component();
            if (grid && Telerik.Web.UI.RadGrid.isInstanceOfType(grid))
                grid = grid.get_masterTableView();
            if (!grid || !Telerik.Web.UI.GridTableView.isInstanceOfType(grid)) {
                debugger;
                throw "Not a 'Telerik.Web.UI.GridTableView'";
            }
            return grid;
        };

        this.showStatusAjaxRequest = function(grid) {
            grid = this._getGrid(grid);
            var i = jQuery.inArray(grid, this._radGrids);
            if (i == -1) {
                this._radGrids.push(grid);
                this._radGridsCounts.push(1);

                var id = grid._statusLabelID;
                if (id) {
                    var e = $get(id);
                    if (e)
                        e.style.visibility = 'visible';
                }
            }
            else {
                this._radGridsCounts[i]++;
            }
        };

        this.hideStatusAjaxRequest = function(grid) {
            grid = this._getGrid(grid);
            var i = jQuery.inArray(grid, this._radGrids);
            if (i !== -1) {
                this._radGridsCounts[i]--;

                if (this._radGridsCounts[i] === 0) {
                    this._radGrids.splice(i, 1);
                    this._radGridsCounts.splice(i, 1);
                    var id = grid._statusLabelID;
                    if (id) {
                        var e = $get(id);
                        if (e)
                            e.style.visibility = 'hidden';
                    }
                }
            }
        };

        this.bind = function(grid, count, items, resetPageIndex) {
            var mt = this._getGridMT(grid);

            if (resetPageIndex)
                mt.set_currentPageIndex(0);

            if (count && items && count > 0) {
                mt.set_virtualItemCount(count);
                mt.set_dataSource(items);
            }
            else {
                mt.set_virtualItemCount(1);
                mt.set_dataSource([]);
                mt.dataBind();
                mt.set_virtualItemCount(0);
            }
            mt.dataBind();

            if (mt._data.PagerAlwaysVisible)
                this._showPager(mt);
        };

        this._showPager = function(mt, jq) {
            if (!jq)
                jq = $(mt.get_element()).find('tr.rgPager td.rgPagerCell');
            jq.css('visibility', 'visible');
            return jq;
        };
        this._hidePager = function(mt, jq) {
            if (!jq)
                jq = $(mt.get_element()).find('tr.rgPager td.rgPagerCell');
            jq.css('visibility', 'hidden');
            return jq;
        };

        this._showPagerRow = function(mt, jq) {
            if (!jq)
                jq = $(mt.get_element()).find('tr.rgPager');
            jq.css('display', '');
            return jq;
        };
        this._hidePagerRow = function(mt, jq) {
            if (!jq)
                jq = $(mt.get_element()).find('tr.rgPager');
            jq.css('display', 'none');
            return jq;
        };

        this.hideNoRecordMsg = function(mt) {
            $(mt.get_element()).find('tr.rgNoRecords').css('display', 'none');
        };

        this.showPagerEx = function(grid, pagerRowVisibility, pagerVisibility) {
            var mt = this._getGridMT(grid);
            var pagerNecessary = (mt.get_pageCount() > 1);

            var showPager = pagerVisibility === GreeNova.GridPagerVisibility.Visible || (pagerNecessary && pagerVisibility === GreeNova.GridPagerVisibility.OnlyIfNecessary);
            var showPagerRow = showPager || pagerRowVisibility === GreeNova.GridPagerVisibility.Visible || (pagerNecessary && pagerRowVisibility === GreeNova.GridPagerVisibility.OnlyIfNecessary);

            if (showPagerRow)
                this._showPagerRow(mt);
            else
                this._hidePagerRow(mt);

            if (showPager)
                this._showPager(mt);
            else
                this._hidePager(mt);
        };

        this.showPager = function(grid, onlyIfNecessary) {
            var mt = this._getGridMT(grid);
            if (onlyIfNecessary) {
                if (mt.get_pageCount() <= 1) {
                    this._hidePager(mt);
                }
                else {
                    this._showPagerRow(mt);
                    this._showPager(mt);
                }
            }
            else {
                this._showPagerRow(mt);
                this._showPager(mt);
            }
        };

        this.showPagerRow = function(grid, onlyIfNecessary) {
            var mt = this._getGridMT(grid);
            if (onlyIfNecessary) {
                if (mt.get_pageCount() <= 1)
                    this._hidePagerRow(mt);
                else
                    this._showPagerRow(mt);
            }
            else
                this._showPagerRow(mt);
            $(mt.get_element()).find('tr.rgPager').css('display', mt.get_pageCount() <= 1 ? 'none' : '');
        };

        this.bindEmpty = function(grid, pagerRowVisibility, pagerVisibility, hideNoRecordMsg) {
            var mt = this._getGridMT(grid);
            mt.set_virtualItemCount(1);
            mt.set_dataSource([]);
            mt.dataBind();
            mt.set_virtualItemCount(0);
            mt.dataBind();

            if (hideNoRecordMsg)
                this.hideNoRecordMsg(mt);
            this.showPagerEx(mt, pagerRowVisibility, pagerVisibility);
        };
        this.getBindingInfo = function(grid, resetPageIndex) {
            var mt = this._getGridMT(grid);

            var pageSize = mt.get_pageSize();
            var currentPageIndex = 0;
            var sort = null;
            if (!resetPageIndex) {
                currentPageIndex = mt.get_currentPageIndex();
                var sortExpressions = mt.get_sortExpressions();
                if (sortExpressions.get_count() === 1) {
                    var s = sortExpressions.getItem(0);
                    sort = {
                        FieldName: s.FieldName,
                        SortOrder: s.SortOrder
                    };
                }
            }
            return {
                PageIndex: currentPageIndex,
                PageSize: pageSize,
                Sort: sort
            };
        };


        this.getNestedElement = function(gridDataItem) {
            if (!gridDataItem)
                return;
            if (!Telerik.Web.UI.GridDataItem.isInstanceOfType(gridDataItem))
                return;
            var ct = gridDataItem.get_owner().get_columns()[0]._data.ColumnType
            if (ct !== 'GridExpandColumn')
                return;
            var e = gridDataItem.get_element();
            return e.parentNode.rows[e.sectionRowIndex + 1].cells[1];
        };

        this.getColumnIndexByUniqueName = function(grid, uniqueName) {
            var mt = this._getGridMT(grid);
            var un = uniqueName.toUpperCase();
            for (var c = 0; c < mt.get_columns().length; c++) {
                if (mt.get_columns()[c].get_element().UniqueName.toUpperCase() == un)
                    return c;
            }
            return null;
        };

        this.getDataItems = function(grid) {
            var mt = this._getGridMT(grid);
            var dis = mt.get_dataItems();
            var vic = mt.get_virtualItemCount();

            var ps = mt.get_pageSize();
            var pc = mt.get_pageCount();
            var pi = mt.get_currentPageIndex();

            if (vic === 0)
                return dis.slice(0, 0);
            else if (pi < (pc - 1)) {
                return dis.slice(0, ps);
            }
            else if (pi === (pc - 1)) {
                var s = ((vic - 1) % ps) + 1;
                return dis.slice(0, s);
            }
        };
    };

    this.RadComboBox = new function() {
        this._getComboBox = function(comboBox) {
            ///	<returns type="Telerik.Web.UI.RadComboBox" />
            if (comboBox && GreeNova.JqueryLookup.isInstanceOfType(comboBox))
                comboBox = comboBox.component();
            if (!comboBox || !Telerik.Web.UI.RadComboBox.isInstanceOfType(comboBox)) {
                debugger;
                throw "Not a 'Telerik.Web.UI.RadComboBox'";
            }
            return comboBox;
        };

        this.showLoadingText = function(comboBox) {
            comboBox = this._getComboBox(comboBox);
            comboBox.set_text('Loading...');
        };

        //        this.bind = function(comboBox, items, itemNameField, itemValueField, addEmptyItem, nameTransform, valueTransform, selectedValue, elementHtmlTransform) {
        //            comboBox = this._getComboBox(comboBox);
        //            this.clear(comboBox);
        //            if (!items)
        //                return;
        //            var item;
        //            if (addEmptyItem) {
        //                item = new Telerik.Web.UI.RadComboBoxItem();
        //                item.set_text('');
        //                item.set_value('');
        //                comboBox.get_items().add(item);
        //                if (selectedValue === undefined)
        //                    item.select();
        //            }

        //            for (var i = 0; i < items.length; i++) {
        //                var e = items[i];
        //                item = new Telerik.Web.UI.RadComboBoxItem();
        //                var name;
        //                var value;
        //                if (nameTransform)
        //                    name = nameTransform(e, i);
        //                else
        //                    name = e[itemNameField];
        //                if (valueTransform)
        //                    value = valueTransform(e, i);
        //                else
        //                    value = e[itemValueField];
        //                item.set_text(name);
        //                item.set_value(value);

        //                item._itemData = e;

        //                comboBox.get_items().add(item);

        //                if (elementHtmlTransform) {
        //                    debugger;
        //                    var el = elementHtmlTransform(e, i);
        //                    $(item.get_element()).html(el);
        //                }

        //                if (!addEmptyItem && i === 0 && selectedValue === undefined)
        //                    item.select();

        //                if (selectedValue !== undefined && value == selectedValue)
        //                    item.select();
        //            }
        //        };

        this.bind = function(comboBox, items, itemName, itemValue, itemElement, addEmptyItem, selectedValue) {
            comboBox = this._getComboBox(comboBox);
            this.clear(comboBox);
            if (!items)
                return;
            var item;
            if (addEmptyItem) {
                item = new Telerik.Web.UI.RadComboBoxItem();
                item.set_text('');
                item.set_value('');
                comboBox.get_items().add(item);
                if (selectedValue === undefined)
                    item.select();
            }

            for (var i = 0; i < items.length; i++) {
                var e = items[i];
                item = new Telerik.Web.UI.RadComboBoxItem();
                var name;
                var value;
                if (itemName !== null && itemName !== undefined) {
                    if ($.isFunction(itemName))
                        name = itemName(e, i);
                    else if (itemName === '')
                        name = e;
                    else
                        name = e[itemName];
                }
                if (itemValue !== null && itemValue !== undefined) {
                    if ($.isFunction(itemValue))
                        value = itemValue(e, i);
                    else if (itemValue === '')
                        value = e;
                    else
                        value = e[itemValue];
                }

                item.set_text(name);
                item.set_value(value);

                item._itemData = e;

                comboBox.get_items().add(item);

                if (itemElement !== null && itemElement !== undefined) {
                    var element;
                    if ($.isFunction(itemElement))
                        element = itemElement(e, i);
                    else
                        element = e[itemElement];
                    $(item.get_element()).html(element);
                }

                if (!addEmptyItem && i === 0 && selectedValue === undefined)
                    item.select();

                if (selectedValue !== undefined && value == selectedValue)
                    item.select();
            }
        };

        this.clear = function(comboBox) {
            comboBox = this._getComboBox(comboBox);
            comboBox.clearItems();
            comboBox.clearSelection();
        };
    };

    this.RadWindow = new function() {
        this.create = function() {
            var wm = Telerik.Web.UI.WindowManager.Manager;
            var d = wm._createWindow(null, null);
            var b = wm.get_element().className;
            if (b)
                d.set_cssClass(b.replace(/^ /, ""));
            return d;
        };
    };

    this.RadDatePicker = new function() {
        this._getDatePicker = function(datePicker) {
            ///	<returns type="Telerik.Web.UI.RadDatePicker" />
            if (datePicker && GreeNova.JqueryLookup.isInstanceOfType(datePicker))
                datePicker = datePicker.component();
            if (!datePicker || !Telerik.Web.UI.RadDatePicker.isInstanceOfType(datePicker)) {
                debugger;
                throw "Not a 'Telerik.Web.UI.RadDatePicker'";
            }
            return datePicker;
        };

        this.toServerDateStr = function(datePicker) {
            ///	<returns type="String" />
            datePicker = this._getDatePicker(datePicker);
            return GreeNova.Utils.toServerDateStr(datePicker.get_selectedDate());
        };

        this.fromServerDateStr = function(datePicker, dateStr) {
            datePicker = this._getDatePicker(datePicker);
            datePicker.set_selectedDate(GreeNova.Utils.fromServerDateStr(dateStr));
        };
    };

    this.AjaxManager = new function() {
        this.createForPM = function(name) {
            return $.manageAjax.create(name, {
                type: "POST",
                url: window.location.pathname + '/PageMethod',
                contentType: "application/json; charset=utf-8",
                dataType: "json",

                queue: true,
                preventDoubbleRequests: false
            });
        };

        this.createForWS = function(name) {
            return $.manageAjax.create(name, {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",

                queue: true,
                preventDoubbleRequests: false
            });
        };
    };

    //this.String = new function() {
    //    this.trim = function(str) {
    //        var m = str.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    //        return m ? m[1] : "";
    //    };

    //    this.trimNull = function(str) {
    //        if (str === undefined || str === null || str.length === 0)
    //            return null;
    //        str = str.trim();
    //        if (str.length === 0)
    //            return null;
    //        return str;
    //    };
    //};

    this.Validators = new function() {
        this._getValidator = function(validator) {
            if (validator && GreeNova.JqueryLookup.isInstanceOfType(validator))
                validator = validator.jq();
            return validator;
        };

        this._enable = function(validator, validateOnEnable) {
            if (validateOnEnable)
                ValidatorEnable(validator, true);
            else
                validator.enabled = true;
        };

        this._disable = function(validator) {
            ValidatorEnable(validator, false);
        };

        this._clear = function(validator) {
            ValidatorEnable(validator, false);
            validator.enabled = true;
        };

        this.enable = function(validator, validateOnEnable) {
            validator = this._getValidator(validator);
            if (!validator)
                return;
            if (validator instanceof jQuery)
                validator.each(function(i, e) { this._enable(e, validateOnEnable); } .setCtx(this));
            else
                this._enable(validator, validateOnEnable);
        };

        this.disable = function(validator) {
            validator = this._getValidator(validator);
            if (!validator)
                return;
            if (validator instanceof jQuery)
                validator.each(function(i, e) { this._disable(e); } .setCtx(this));
            else
                this._disable(validator);
        };

        this.clear = function(validator) {
            validator = this._getValidator(validator);
            if (!validator)
                return;
            if (validator instanceof jQuery)
                validator.each(function(i, e) { this._clear(e); } .setCtx(this));
            else
                this._clear(validator);
        };
    };
};
